var express = require('express');
var router = express.Router();
const {User,Equipment,Laboratory} = require('../../models')
const {success,failure} = require('../../util/requestResult')
const {NotFoundError,BadRequestError,UnauthorizedError,AlreadyExistsError,SequelizeValidateError} = require('../../util/errors')
// 查询条件限制
const condition = {
    include:[
        {
            model:Laboratory,
            as:'Laboratory',
            attributes:['id','laboratoryName']
        }
    ]
}
// 查询所有设备
router.get('/',async function(req,res,next){
    try {
        let equipment = await Equipment.findAll(condition)
        success(res,'查询所有设备成功',equipment)
    } catch (error) {
        failure(res,error)
    }

})

// 按id查找设备
router.get('/:id',async function(req,res,next){
    try {
        let equipment = await getequipment(req,true)
        success(res,`查询id为${req.params.id}的设备成功`,equipment)
    } catch (error) {
        failure(res,error)
    }

})

// 新增设备
router.post('/',async function(req,res,next){
    try {
        let equipmentInfo = filterBody(req)
        let createdEquipment = await Equipment.create(equipmentInfo)
        success(res,'创建设备成功',createdEquipment,201)
    } catch (error) {
        failure(res,error)
    }

})

// 更新设备
router.put('/:id',async function(req,res,next){
    try {
        let equipmentInfo = filterBody(req)
        let equipment = await getequipment(req)
        await equipment.update(equipmentInfo)
        success(res,`更新id为${req.params.id}设备成功`,equipment)
    } catch (error) {
        failure(res,error)
    }

})


// 删除设备
router.delete('/:id',async function(req,res,next){
    try {
        let equipment = await getequipment(req)
        await equipment.destroy()
        success(res,`删除id为${req.params.id}设备成功`)
    } catch (error) {
        failure(res,error)
    }

})


function filterBody(req){
    let {laboratoryId,equipmentName,openTime,closeTime,isApplyBook} = req.body
    return {laboratoryId,equipmentName,openTime,closeTime,isApplyBook}
}


async function getequipment(req,isCondition){
    const {id} = req.params
    let equipment = await Equipment.findByPk(id,isCondition?condition:{})
    if(!equipment)
        throw new NotFoundError(`未查询到id为${id}的设备`)
    return equipment
}

module.exports = router